package com.example.smartcity_poverty.ui.AllService.SmartBus

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.ServiceBean.SmartBus.BusPathModel
import com.example.smartcity_poverty.logic.util.Util
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.ui.AllService.SmartBus.adapter.BusHomeRecyclerAdapter
import kotlinx.android.synthetic.main.activity_smart_bus.*
import kotlinx.coroutines.Dispatchers

/**
 * 智慧巴士功能模块开发
 */
class SmartBusActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_smart_bus)
        title = "智慧巴士"


        // 启动协程
        runCoroutine()
    }

    /**
     * 协程管理
     */
    private fun runCoroutine() = coroutine(Dispatchers.IO){
        // 网络获取主页列表信息
        setBusHomeRecycler()
    }

    /**
     * 网络获取主页列表信息
     */
    private suspend fun setBusHomeRecycler() {
        // 获取网络数据
        val result = api.getBusPath()
        // 判断是否获取数据成功
        if (result.code == 200){
            runOnUiThread {
                // 列表适配器设置
                busHomeRecyclerView.apply {
                    this.layoutManager = LinearLayoutManager(context)
                    this.adapter = BusHomeRecyclerAdapter(ArrayList<BusPathModel.RowsBean>().apply {
                        this.addAll(result.rows!!)
                    }, R.layout.re_bus_home_recycler)
                }
            }
        }else runOnUiThread { result.msg?.show() }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}